<template>
  <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-by-phone">
    <el-form-item prop="username">
      <el-input v-model="loginForm.phone" type="text" auto-complete="off" placeholder="手机号">
        <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
      </el-input>
    </el-form-item>
    <el-form-item prop="code">
      <el-input
        v-model="loginForm.code"
        auto-complete="off"
        placeholder="验证码"
        style="width: 58%"
        @keyup.enter.native="handleLogin"
      >
        <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
      </el-input>
      <verification-button style="margin-left: 10px; float: right" :phone="loginForm.phone"></verification-button>
    </el-form-item>
    <el-form-item style="width:100%;">
      <el-button
        :loading="loading"
        size="medium"
        type="primary"
        style="width:100%;"
        @click.native.prevent="handleLogin"
      >
        <span v-if="!loading">登 录</span>
        <span v-else>登 录 中...</span>
      </el-button>
    </el-form-item>
  </el-form>
</template>
<script>
  import VerificationButton from './VerificationButton'
  export default {
    name:"LoginByPhone",
    components: { VerificationButton },
    data(){
      return {
        redirect: undefined,
        loading:false,
        loginForm: {
          phone: "",
          code: "",
        },
        loginRules: {
          phone: [
            { required: true, trigger: "blur", message: "手机号不能为空" }
          ],
          code: [{ required: true, trigger: "change", message: "验证码不能为空" }]
        },
      }
    },
    watch: {
      $route: {
        handler: function(route) {
          this.redirect = route.query && route.query.redirect;
        },
        immediate: true
      }
    },
    methods:{
      handleLogin() {
        this.$refs.loginForm.validate(valid => {
          if (valid) {
            this.loading = true;
            this.$store.dispatch("user/loginByCode", this.loginForm).then(() => {
              console.log("============this.redirect=",this.redirect)
              this.$router.push({ path: this.redirect || "/" }).catch(()=>{});
            }).catch(() => {
              this.loading = false;
            });
          }
        });
      }
    }
  }
</script>
<style lang="scss" scoped>
  .login-by-phone{
    height: 300px;
  }
</style>
